#include "c8051f330.h"
#include "BLMC.h"
#include "AppGlobalData.h"
#include "define.h"
#include "misc.h"
#include "structdefine.h"
//-----------------------------------------------------------------------------
// 16-bit SFR Definitions for 'F30x
//----------------------------------------------------------------------------- 

//-----------------------------------------------------------------------------
// Interrupt Service Routines
//-----------------------------------------------------------------------------


#define INT0_ACTIVE_HI()		IT01CF = 0x0E
#define INT0_ACTIVE_LOW()		IT01CF = 0x06
#define INT0_ACTIVE_TOOGLE()	((IT01CF&0x08)? (IT01CF = 0x06) : (IT01CF = 0x0E)) 
//extern interrupt0 Service Routines
// Throttle Pulse width measure


void INT0_ISR (void) interrupt 0
{
	IE0  = 0 ;
	if(IT01CF&0x08)
	{
		TMR3L = 0;
		TMR3H = 0;
		///Blink = 1;
		TMR3CN |= 0x04;
	}
	else
	{
		TMR3CN &= 0xFB;
		//Blink = 0;
		ThrottleFilter = (uint16_t)(TMR3H<<8) + TMR3L;
		ThrottleFilter /= 2;//uint 0.4898us
		Throttle = Throttle + (ThrottleFilter - Throttle)/8;
		if(!ThroSignalOK)
		{
			ThroSignalOK = 1;
		}			
	}		
	INT0_ACTIVE_TOOGLE();
}

//-----------------------------------------------------------------------------
// Time0 int every 20ms
//-----------------------------------------------------------------------------
void Time0_ISR (void) interrupt 1
{
	TF0 = 0 ;                        //clear TF0

}



//extern interrupt1 Service Routines
//
void INT1_ISR (void) interrupt 2
{

	IE1  = 0 ;
	
}
extern void commutate(void);
extern void MotorControl(void);
void Time1_ISR (void) interrupt 3
{
	TF1 = 0 ;                        //clear TF0
	
	if(SystemState == Commutate)
	{  LEDR = ~LEDR;
		commutate(); // commutate
		CommutateState = Synchronoused;
		TL1 = 0x00;
		TH1 = 0x00;
	}
}


void CCF_ISR(void) interrupt 11  
{ 	
	
	if(CCF1)//PWW ON interrupt
	{
		CCF1 = 0;
		MotorControl();
	}
	else
	//if(CF) //PWW OFF interrupt
	{
		CF = 0;
		DIS_PCA0;
		if(gNotFullThro)
		{
			PCA0L = PCA0L_RELOAD;
			PCA0H = PCA0H_RELOAD;
		}
		else
		{
			PCA0L = PCA0L_RELOAD_100PWM;
			PCA0H = PCA0H_RELOAD_100PWM;		
		}
		EN_PCA0;

	}

} 
//-----------------------------------------------------------------------------
// Time0 int
//-----------------------------------------------------------------------------
void Timer2_ISR (void) interrupt 5
{
	TF2H = 0;                              // clear Timer2 interrupt flag
	TM2_INT_FLAG = INT_ARRIVE;
} 

//-----------------------------------------------------------------------------
// Time0 int
//-----------------------------------------------------------------------------
void Timer_ISR (void) interrupt 14
{
	TMR3CN &= 0x7f ;                        //clear TR3H
	
}